import ImgWasm, { convert } from '/wasm/imgConvert/img_convert.js?url'
import LZ4, { compress, decompress } from '/wasm/lz4/rs_lz4.js?url'
export { convert, compress, decompress, ImgWasm, LZ4 }

import { AlexMsg } from '@2473o/alexui'

// 压缩 LZ4 数据
export const compressLZ4 = async (arrayBuffer) => {
  try {
    const uint8Array = new Uint8Array(arrayBuffer)
    // console.log('Calling compress with data:', uint8Array)
    const compressedData = compress(uint8Array)
    return compressedData
  } catch (error) {
    throw new Error('Compression failed: ' + error.message)
  }
}
// 解压缩 LZ4 数据
export const decompressLZ4 = async (arrayBuffer) => {
  try {
    const uint8Array = new Uint8Array(arrayBuffer)
    // console.log("Calling decompress with data:", uint8Array);
    const decompressedData = decompress(uint8Array)
    return decompressedData
  } catch (error) {
    throw new Error('Decompression failed: ' + error.message)
  }
}

// 图片转换
export const convertImage = async (file, convertType) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = async (event) => {
      const arrayBuffer = event.target.result
      const imageData = new Uint8Array(arrayBuffer)

      try {
        const convertedData = convert(imageData, convertType)
        const blob = new Blob([convertedData], { type: `image/${convertType}` })
        resolve(blob)
      } catch (err) {
        AlexMsg({
          type: 'error',
          text: `Failed to convert image: ${err}`
        })
        console.error('Failed to convert image:', err)
        reject(err)
      }
    }
    reader.readAsArrayBuffer(file)
  })
}
